<?php

/**
 * 文档章节模型
 *
 * @author 煤老板 <meok23@sina.com>
 * @date   2017-06-06
 */

namespace app\admin\model;

use app\common\logic\Response;
use fw\base\Instance;
use fw\db\DB;
use fw\tool\Request;
use fw\tool\Url;

class Chapter
{
    use Instance;

    /**
     * 新增一条数据
     *
     * @return array
     */
    public function add()
    {
        // 参数获取
        $title = Request::post('title', 'trim');
        $parent_id = (int)Request::post('parent_id');
        $doc_id = (int)Request::post('doc_id');
        $content = Request::post('content', 'trim');
        $manager_id = (int)Request::post('manager_id');
        $types = Request::post('types', 'trim', 'content');

        // 参数校验
        if (empty($title) || $doc_id < 1 || !in_array($types, ['content', 'dir'])) {
            return Response::to([400, 'Parameter error.']);
        }
        if ($parent_id > 0) {
            $ret = $this->getInfo(['chapter_id' => $parent_id]);
            if ($ret['types'] !== 'dir') {
                return Response::to([400, 'This record is not dir.']);
            }
        }

        // 操作数据库
        $data = [
            'title'       => $title,
            'parent_id'   => $parent_id,
            'doc_id'      => $doc_id,
            'content'     => $content,
            'manager_id'  => $manager_id,
            'create_time' => time(),
            'update_time' => 0,
            'types'       => $types,
        ];
        $ret = DB::table('chapter')->insert($data);
        if ($ret == false) {
            return Response::log([500, 'Insert fail.'], Request::post());
        }
        $chapter_id = (int)$ret;

        return Response::to([0, 'Success.', ['chapter_id' => $chapter_id]]);
    }

    /**
     * 更新一条数据
     *
     * @param $args
     *
     * @return array
     */
    public function update($args = null)
    {
        empty($args) && $args = $_POST;

        // 参数获取
        $chapter_id = (int)Request::input($args, 'chapter_id');
        $title = Request::input($args, 'title', 'trim');
        $parent_id = (int)Request::input($args, 'parent_id');
        $doc_id = (int)Request::input($args, 'doc_id');
        $content = Request::input($args, 'content', 'trim');
        $manager_id = (int)Request::input($args, 'manager_id');

        $sort = (int)Request::input($args, 'sort');

        // 参数校验
        if ($chapter_id < 1 || $manager_id < 1) {
            return Response::to([400, 'Parameter error.']);
        }

        // 数据准备
        $data = [];
        if (!empty($title)) {
            $data['title'] = $title;
        }
        if ($parent_id > 0) {
            $data['parent_id'] = $parent_id;
        }
        if ($doc_id > 0) {
            $data['doc_id'] = $doc_id;
        }
        if (!empty($content)) {
            $data['content'] = $content;
        }
        if ($manager_id > 0) {
            $data['manager_id'] = $manager_id;
        }
        if ($sort > -1) {
            $data['sort'] = $sort;
        }

        if (empty($data)) {
            return Response::to([400, 'Parameter error, data empty.']);
        }

        $data['update_time'] = time();
        $affected_rows = DB::table('chapter')->where('chapter_id=:chapter_id', [':chapter_id' => $chapter_id])->update($data);
        if ($affected_rows == false) {
            return Response::to([200, 'Without any modification.', $data]);
        }

        return Response::to([0, 'Success.']);
    }

    /**
     * 获取一条数据
     *
     * @param array $args
     *
     * @return array
     */
    public function getInfo($args)
    {
        // 参数获取
        $chapter_id = (int)Request::input($args, 'chapter_id');
        $doc_id = (int)Request::input($args, 'doc_id');

        $ret = [];
        if ($chapter_id > 0) {
            $ret = DB::table('chapter')->where('chapter_id=:chapter_id', [':chapter_id' => $chapter_id])->selectRow();
        } elseif ($doc_id > 0) {
            $ret = DB::table('chapter')->where('doc_id=:doc_id', [':doc_id' => $doc_id])->order('sort')->selectRow();
        }

        return $ret;
    }

    /**
     * 获取列表或统计条数
     *
     * @param array $args
     *
     * @return array|int
     */
    public function getList($args)
    {
        // 参数获取
        $chapter_ids = Request::input($args, 'chapter_ids', 'trim');
        $doc_id = (int)Request::input($args, 'doc_id');

        $page = Request::input($args, 'page', 'intval', 1);
        $length = Request::input($args, 'length', 'intval', 100);

        $sort_way = Request::input($args, 'sort_way', 'trim', 'DESC');
        $sort_way = strtoupper($sort_way);

        $is_count = Request::input($args, 'is_count', 'boolval', false);

        // 条件组装
        $prep = $map = [];
        if (!empty($chapter_ids)) {
            $map[] = 'chapter_id IN (:chapter_id)';
            $prep[':chapter_id'] = $chapter_ids;
        }
        if ($doc_id != 0) {
            $map[] = 'doc_id=:doc_id';
            $prep[':doc_id'] = $doc_id;
        }
        $where = implode(' AND ', $map);

        // 查询条数
        if ($is_count === true) {
            return DB::table('chapter')->where($where, $prep)->count();
        }

        // 查询列表
        $rows = DB::table('chapter')
            ->where($where, $prep)
            ->order('sort ' . $sort_way)
            ->limit(($page - 1) * $length . ',' . $length)
            ->select();

        return $rows;
    }

    /**
     * 章节树
     *
     * @param array $rows
     * @param int   $parent_id
     *
     * @return string
     */
    public function ChapterTree($rows, $parent_id = 0)
    {
        $html = '';
        foreach ($rows as $k => $v) {
            if ($v['parent_id'] == $parent_id) {
                $url_add = Url::to('Chapter/add', ['doc_id' => $v['doc_id'], 'parent_id' => $v['chapter_id']]);
                $url_update = Url::to('Chapter/update', ['doc_id' => $v['doc_id'], 'chapter_id' => $v['chapter_id']]);
                $chapter_id = $v['chapter_id'];

                $btn = '<a class="tree-del" data-id="' . $chapter_id . '" href="javascript:;" onclick="del(this);"></a>';
                if ($v['types'] === 'dir') {
                    $btn .= '<a class="tree-add" href="' . $url_add . '"></a>';
                    $title = '<a class="tree-dir" href="' . $url_update . '">' . $v['title'] . '</a>';
                } else {
                    $title = '<a class="tree-content" href="' . $url_update . '">' . $v['title'] . '</a>';
                }

                $html .= '<li data-id="' . $chapter_id . '"><p>' . $title . '<label>' . $btn . '</label>' . '</p>';
                $html .= $this->ChapterTree($rows, $v['chapter_id']);
                $html = $html . '</li>';
            }
        }

        return $html ? '<ul id="sortable">' . $html . '</ul>' : $html;
    }

    /**
     * 递归模拟 path 路径排序
     *
     * @param array  $rows      源数组
     * @param int    $parent_id 上级id
     * @param string $title     上级标题
     *
     * @return array
     */
    public function TreeWithTitle($rows, $parent_id = 0, $title = '')
    {
        $arr = [];

        foreach ($rows as $v) {
            if ($v['parent_id'] == $parent_id) {
                $v['title'] = $title . '/' . $v['title'];
                $arr[] = $v;
                $arr = array_merge($arr, $this->TreeWithTitle($rows, $v['chapter_id'], $v['title']));
            }
        }

        return $arr;
    }

    /**
     * 删除数据
     *
     * @param $args
     *
     * @return array
     */
    public function del($args)
    {
        // 参数获取
        $chapter_id = (int)Request::input($args, 'chapter_id');
        $op_user = (int)Request::input($args, 'op_user');

        // 参数校验
        if ($chapter_id < 1 || $op_user < 1) {
            return Response::to([400, 'Parameter error.']);
        }

        // 查询信息
        $info = DB::table('chapter')->where('chapter_id=:chapter_id', [':chapter_id' => $chapter_id])->selectRow();
        if (empty($info)) {
            return Response::to([404, 'Record does not exist.']);
        }

        // 放入回收站
        Recy::gi()->add('chapter', $info, $op_user);

        // 删除数据
        $affected_rows = DB::table('chapter')->where('chapter_id=:chapter_id', [':chapter_id' => $chapter_id])->delete();
        if ($affected_rows == false) {
            return Response::log([500, 'Delete fail.', ['chapter_id' => $chapter_id]], $args);
        }

        // 更新子章节
        DB::table('chapter')->where('chapter_id=:chapter_id', [':chapter_id' => $chapter_id])->update(['parent_id' => $info['parent_id']]);

        return Response::to([0, 'Success.']);
    }

    /**
     * 清空某个文档的所有章节
     *
     * @param $args
     *
     * @return array
     */
    public function truncate($args)
    {
        // 参数获取
        $doc_id = (int)Request::input($args, 'doc_id');
        $op_user = (int)Request::input($args, 'op_user');

        // 参数校验
        if ($doc_id < 1 || $op_user < 1) {
            return Response::to([400, 'Parameter error.']);
        }

        // 查询信息
        $rows = DB::table('chapter')->where('doc_id=' . $doc_id)->select();
        if (empty($rows)) {
            return Response::to([404, 'Record does not exist.']);
        }

        // 放入回收站
        foreach ($rows as $info) {
            Recy::gi()->add('chapter', $info, $op_user);
        }

        // 删除数据
        $affected_rows = DB::table('chapter')->where('doc_id=' . $doc_id)->delete();
        if ($affected_rows == false) {
            return Response::log([500, 'Delete fail.'], $args);
        }

        return Response::to([0, 'Success.']);
    }
}
